package shapewar.view.myview;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;
import shapewar.activities.FrameActivity;
import shapewar.conf.Conf;
import shapewar.engine.calc.Pos;
import shapewar.engine.model.abst.Model;
import shapewar.engine.presenter.Presenter;
import shapewar.view.intefac.IMyView;

public class MyView extends View implements IMyView{
	public static final int other_view = 0;
	public static final int tank_view = 1;
	public static final int bullet_view = 2;
	public static final int protector_view = 3;
	private InvalidateThread ithread = new InvalidateThread();
	public Presenter pst;
	public static float rate = 1.0f;
	private Model shape;
	public MyView(Presenter pst,Model shape) {
		super(FrameActivity.context);
		this.pst = pst;
		this.shape = shape;
		if(shape!=null)
			shape.setView(this);
		//paint.setAntiAlias(true);
		ithread.start();
	}
	
	public void setModel(Model model){
		this.shape = model;
	}
	public Model getModel(){
		return shape;
	}
	
	public static Pos playerPos = new Pos(0,0);
	public Pos getRelativePos() {
		if(pst.ect.player!=null)
			playerPos = pst.ect.player.getPos();
		//if(shape==null)return playerPos;
		return new Pos((shape._x - playerPos.x)*rate + Conf.frame_width/2
				,(shape._y - playerPos.y)*rate + Conf.frame_height/2);
	}
	
	float nearDis = -100;
	public boolean isNearFrameWindow() {
		Pos pos = getRelativePos();
		return pos.x>nearDis&&pos.y>nearDis&&(pos.x<Conf.frame_width-nearDis)&&pos.y<(Conf.frame_height-nearDis);
	}
	
	@Override
	public void invalidate() {
		ithread.add(this);
	}
	
	public void doinvalidate(){
		super.invalidate();
	}
	
	@Override
	public void resize(float rate) {
		MyView.rate = rate;
		invalidate();
	}
	
	protected Paint paint = new Paint();
	@Override
	protected void onDraw(Canvas canvas) {
		if (!isNearFrameWindow())return;
		float v[][] = shape.getV();
		if(v==null)return;
		Path path = new Path();
		float x = getRelativePos().x,y = getRelativePos().y;
		double ratio = Math.PI / 180;
		double r = Math.sqrt(v[0][0]*v[0][0] + v[0][1]*v[0][1]) * rate;
		path.moveTo((float)(x + r * Math.cos((shape._rotation) * ratio + Math.atan2(v[0][1], v[0][0]))),(float)(y - r*Math.sin((shape._rotation) * ratio + Math.atan2(v[0][1], v[0][0]))));
		for(int i=1;i<v.length;i++){
			r = Math.sqrt(v[i][0]*v[i][0] + v[i][1]*v[i][1]) * rate;
			path.lineTo((float)(x + r * Math.cos((shape._rotation) * ratio + Math.atan2(v[i][1], v[i][0]))),(float)(y - r*Math.sin((shape._rotation) * ratio + Math.atan2(v[i][1], v[i][0]))));
		}
		path.close();
		canvas.drawPath(path,paint);
	}
}
 